package jTopaz;

import java.util.Timer;
import java.io.File;
import java.util.TimerTask;

/**
Handles monitoring the speed/progress of a download.
*/
public class LocalFileMonitor {

    private String fileName;
    private long size;
    private Timer timer;
    private LocalMonitorTask task;
    private double progress;
    private double speed;

    /**
    @param fileName the name of the local file to poll.
    @param the total size of the remote file (the end size)
    */
    public LocalFileMonitor(String fileName, long size) {
		this.fileName = fileName;
		this.size = size;
		this.task = new LocalMonitorTask(fileName, size, 0, 0, 0);
		timer = new Timer(true);
		progress = 0;
		speed = 0;
    }

    /**
    Creates a local file task that is run every second.
    */
    public void run() {
		long delay = 0;
		long period = 1000;
		timer.schedule(task, delay, period);
    }

    /**
    stops the task
    */
    public void stop() {
		timer.cancel();
    }

	/**
	gets the current speed
	*/
    public double getSpeed() {
		return task.getSpeed();
    }
    
    /**
    gets the current progress
    */
    public double getProgress() {
		return task.getProgress();
    }
}

class LocalMonitorTask extends TimerTask{

    private String fileName;
    private double size;
    private double previous;
    private File file;
    private double currentSize;
    double progress;
    private double speed;

    public LocalMonitorTask(String fileName, long size, double currentSize, double progress, double speed) {
	this.fileName = fileName;
	this.size = new Long(size).doubleValue();
	file = new File(fileName);
	previous = 0;
	this.currentSize = currentSize;
	this.speed = speed;
    }

    public void run() {

	try {
	    //recreate the file (necessary to get the new size)
	    file = new File(fileName);

	    //get the current size
	    currentSize = new Long(file.length()).doubleValue();
	    //System.out.println(currentSize);
	    //System.out.println("total size: " + size);
	    //get the change - calculate speed
	    double change = currentSize - previous;
	    speed = change/1024;
	    //System.out.println("Speed: " + speed);
	    //System.out.println("total size: " + size);
	    progress = currentSize/size * 100;
	    //System.out.println("Progress: " + progress + "%\n");
	    
	    //update values
	    previous = currentSize;
	}

	catch (Exception e) {
	    System.out.println(e);
	    e.printStackTrace();
	}
    }

    public double getSpeed() {
	return speed;
    }

    public double getProgress() {
	return progress;
    }
}
